package com.mini6410.EEPROM;

import android.os.Handler;
import android.util.Log;

import com.friendlyarm.AndroidSDK.HardwareControler;

public class ReadEEPROM{
	private static final String TAG = "WriteEEPROM";

	private static final int MAX_LENGTH = 256; //EEPROM最多可存储256个字节数据

	Handler mHandler = null;

	private ReadEEPROMThread mReadEEPROMThread = null;

	public ReadEEPROM(Handler mHandler){
		this.mHandler = mHandler;
	}

	public void ReadData(){
		safeStop();

		mReadEEPROMThread = new ReadEEPROMThread();
		mReadEEPROMThread.start();
	}

	public void safeStop(){
		if(mReadEEPROMThread != null && mReadEEPROMThread.isAlive()){
			mReadEEPROMThread.interrupt();
			mReadEEPROMThread.stop = true;
			try {
				mReadEEPROMThread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		mReadEEPROMThread = null;
	}

	public void sendMessage(int what ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what));
		}	
	}

	public void sendMessage(int what, Object obj ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what, obj));
		}
	}

	public void sendMessage(int what, int arg1,int arg2,Object obj ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj));
		}
	}

	
	public void sendMessage(int what, int arg1,int arg2 ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2));
		}
	}
	
	private class ReadEEPROMThread extends Thread{
		volatile boolean stop = false;

		int fd = 0; 
		int length = 0;
		int pos = 0;
		byte data = 0;

		@Override
		public void run() {

			fd = HardwareControler.openI2CDevice();

			if(fd == -1)
			{
				Log.e(TAG, "Failed to open the I2CDevice !");

				stop = true;
			}

			length = MAX_LENGTH;

			while(!stop){
			
				if (pos >= length) {
					break;
				}
				
				data = (byte)HardwareControler.readByteDataFromI2C(fd, pos);
				
				sendMessage(EEPROMActivity.MSG_GET_DATA, data);
				sendMessage(EEPROMActivity.MSG_UPDATE_UI, pos,length);
		
				Log.i(TAG, "readByteDataFromI2C pos: "+ pos);
				
				pos++;

//				try {
//					Thread.sleep(10);
//				} catch ( InterruptedException e ) {
//					e.printStackTrace();
//				}

			}

			if(fd != -1)
			{
				HardwareControler.close(fd);
			}
		}
	}
}
